﻿using System;
using Core.AdminGroupMenuPermission;
using Core.Authenticated;
using Core.Library;
using DataObject;
using DataObject.News;
using DataObject.TagDetails;

namespace CMS.Controls.News
{
    public partial class CreateOrEdit : AuthenticatedControl
    {
        protected string ReturnUrl;
        protected string CurrentTab;
        protected string Action;
        protected string Body;

        protected string Content;

        protected void Page_Load(object sender, EventArgs e)
        {
            ReturnUrl = Utils.GetIdFromRequestString(Utils.ReturnUrl, string.Empty);
            Action = Utils.GetIdFromRequestString(Utils.Action, string.Empty);

            if (!IsPostBack)
            {
                var id = Utils.GetLongIdFromRequestString(Utils.Id, 0);
                ltTitle.Text = id > 0 ? "Sửa bài viết" : "Tạo mới bài viết";

                ActionPermission();
                hfUsername.Value = CurrentUser.Username;
                if (id > 0)
                    BindObject(id);
            }
        }

        private void BindObject(long id)
        {
            var o = NewsController.News_GetById(id);
            if (o == null) return;

            txtTitle.Text = o.News_Title;
            txtSapo.Text = o.News_Sapo;
            txtSubTitle.Text = o.News_Subtitle;
            txtImage.Text = o.News_Image;
            txtImageHomePage.Text = o.News_ImageHomePage;
            txtBody.Text = o.News_Content;
            cbIsHomePage.Checked = o.News_HomePageFocus;
            cbIsList.Checked = o.News_ListFocus;
            cbIsBox.Checked = o.News_BoxFocus;
            txtPenName.Text = o.News_PenName;
            ddlCategory.SelectedValue = o.Cat_ID.ToString();
            txtPublishOn.Text = DateTimeFunctions.FormatDateVietNam(o.News_PublishDate);
            txtTime.Text = DateTimeFunctions.FormatTimeVietNam(o.News_PublishDate);
            

            hfId.Value = id.ToString();
            hfTypeId.Value = ((int)NewsType.Normal).ToString();
        }

        public void ActionPermission()
        {
            var isShowPublished = false;

            var adminGroupMenuPermission =
                    AdminGroupMenuPermissionController.AdminGroupMenuPermission_GetBy_AdminUserId_AdminMenuId(CurrentUser.AdminUserId, cControl.AdminMenuId);
            if (adminGroupMenuPermission.Count > 0)
            {
                foreach (var agmp in adminGroupMenuPermission)
                {
                    isShowPublished = StatusHelper.IsChecked(agmp.Status, (int)PermissionObject.CanPublish);
                }

                //if (isHighlightHomePage)
                //    ddlHighlights.Items.Add(new ListItem("Nổi bật Trang chủ", "256"));
                //if (isHighlightCategory)
                //    ddlHighlights.Items.Add(new ListItem("Nổi bật Chuyên mục", "128"));
            }

            foreach (var t in Utils.Tabs)
                if (ReturnUrl.IndexOf(t) != -1)
                    CurrentTab = t;

            if (!string.IsNullOrEmpty(CurrentTab))
            {
                // Nếu action là Tạo mới thì nút Save mới được hiển thị
                if (Action.ToLower().Equals("create"))
                    CurrentTab = Utils.IsDraft;

                switch (CurrentTab)
                {
                    // Đã gỡ                        
                    case "IsRemoved":
                        btnPublish.Visible = isShowPublished;
                        btnSend.Visible = true;
                        btnRestore.Visible = isShowPublished;
                        break;
                    // Chờ duyệt                        
                    case "IsWaitingForPublish":
                        btnPublish.Visible = isShowPublished;
                        btnSaveWithoutStatus.Visible = true;
                        break;
                    // Trả lại                        
                    case "IsReturned":
                        btnPublish.Visible = isShowPublished;
                        btnSend.Visible = true;
                        btnDelete.Visible = true;
                        break;
                    // Xuất bản                        
                    case "IsPublished":
                        btnRemove.Visible = isShowPublished;
                        btnSaveWithoutStatus.Visible = isShowPublished;
                        break;
                    // Lưu tạm                        
                    case "IsDraft":
                        btnPublish.Visible = isShowPublished;
                        btnSend.Visible = true;
                        btnSave.Visible = true;
                        btnDelete.Visible = !Action.ToLower().Equals("create");
                        btnSaveAndContinue.Visible = true;
                        break;
                }
            }
            else
            {
                btnSend.Enabled = false;
                btnPublish.Enabled = false;
                btnDelete.Enabled = false;
                btnRemove.Enabled = false;
            }
        }

        public void ManagerAction(string action)
        {

            if (CheckIsBase64())
            {
                ltMessage.Text = MessageUtility.ShowMessage(string.Empty,
                                            "Không được phép sử dụng hình ảnh base 64!",
                                            MessageType.Failure);
                return;
            }

            NewsObject o;

            var tag = hfTag.Value;
            var currentStatus = 0;
            long id = Utils.GetLongIdFromRequestString(Utils.Id, 0);
            var publishOn = DateTimeFunctions.ValidDateTime(txtPublishOn.Text, txtTime.Text);
            var cat = ConvertUtility.ConvertTo<int>(ddlCategory.SelectedValue);

            switch (action)
            {
                case Const.Action.Save:
                    currentStatus = StatusHelper.IsDraft;
                    break;
                case Const.Action.Send:
                    currentStatus = StatusHelper.IsWaitingForPublish;
                    break;
                case Const.Action.Publish:
                    currentStatus = StatusHelper.IsPublished;
                    break;
                case Const.Action.Remove:
                    currentStatus = StatusHelper.IsRemoved;
                    break;
                case Const.Action.SaveAndContinue:
                    currentStatus = StatusHelper.IsDraft;
                    break;
                case Const.Action.Restore:
                    currentStatus = StatusHelper.IsDraft;
                    break;
            }

            if (id > 0)
            {
                o = NewsController.News_GetById(id);

                o.News_ID = id;
                o.Cat_ID = cat;
                o.News_Title = txtTitle.Text;
                o.News_Sapo = txtSapo.Text;
                o.News_Subtitle = txtSubTitle.Text;
                o.News_Image = txtImage.Text;
                o.News_ImageHomePage = txtImageHomePage.Text;
                o.News_Content = txtBody.Text;
                o.News_Type = (int)NewsType.Normal;
                o.News_UserID = 0;
                o.News_HomePageFocus = cbIsHomePage.Checked;
                o.News_ListFocus = cbIsList.Checked;
                o.News_BoxFocus = cbIsBox.Checked;
                o.News_PenName = txtPenName.Text;
                o.News_Video = string.Empty;
                o.News_VideoTitle = string.Empty;
                o.News_PublishDate = publishOn;
                o.News_EditedBy = CurrentUser.Username;
                if (action != Const.Action.SaveWithoutStatus && action != Const.Action.SaveAndContinue)
                {
                    o.News_Status = currentStatus;
                    o.News_ApprovedDate = DateTime.Now;
                    o.News_ApprovedBy = CurrentUser.Username;
                }
                if (o.News_ApprovedDate < Constants.MinDate) o.News_ApprovedDate = DateTime.Now;
                NewsController.News_Update(o);

                // delete old tag
                TagDetailsController.TagDetails_DeleteById_TypeId(id, (int)NewsType.Normal);
            }
            else
            {
                o = new NewsObject();

                o.News_ID = Utils.BuildNewsID();
                o.Cat_ID = cat;
                o.News_Title = txtTitle.Text;
                o.News_Sapo = txtSapo.Text;
                o.News_Subtitle = txtSubTitle.Text;
                o.News_Image = txtImage.Text;
                o.News_ImageHomePage = txtImageHomePage.Text;
                o.News_Content = txtBody.Text;
                o.News_Status = currentStatus;
                o.News_Type = (int)NewsType.Normal;
                o.News_UserID = 0;
                o.News_HomePageFocus = cbIsHomePage.Checked;
                o.News_ListFocus = cbIsList.Checked;
                o.News_BoxFocus = cbIsBox.Checked;
                o.News_PenName = txtPenName.Text;
                o.News_Video = string.Empty;
                o.News_VideoTitle = string.Empty;
                o.News_PublishDate = publishOn;
                o.News_CreatedBy = CurrentUser.Username;

                NewsController.News_Create(o);
                id = o.News_ID;
            }

            if (id > 0)
            {
                // list tag
                string[] splitTag = tag.Split(',');
                if (splitTag.Length > 0)
                {
                    for (var i = 0; i < splitTag.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(splitTag[i]))
                        {
                            //lstTag.Add(Int32.Parse(splitTag[i]));
                            var t = new TagDetailsObject();
                            t.Id = id;
                            t.TagId = Int32.Parse(splitTag[i]);
                            t.TypeId = (int)NewsType.Normal;
                            var a = TagDetailsController.TagDetails_Create(t);
                        }
                    }
                }
            }

            if (action != Const.Action.SaveAndContinue) Response.Redirect(ReturnUrl);
        }

        private bool CheckIsBase64()
        {
            return txtBody.Text.Contains(";base64,");
        }

        #region Buttons

        protected void BtnSave(object sender, EventArgs e)
        {
            ManagerAction(Const.Action.Save);
        }

        protected void BtnSaveWithoutStatus(object sender, EventArgs e)
        {
            ManagerAction(Const.Action.SaveWithoutStatus);
        }

        protected void BtnSaveAndContinue(object sender, EventArgs e)
        {
            ManagerAction(Const.Action.SaveAndContinue);
        }

        protected void BtnSend(object sender, EventArgs e)
        {
            ManagerAction(Const.Action.Send);
        }

        protected void BtnPublish(object sender, EventArgs e)
        {
            ManagerAction(Const.Action.Publish);
        }

        protected void BtnRestore(object sender, EventArgs e)
        {
            ManagerAction(Const.Action.Restore);
        }

        protected void BtnRemove(object sender, EventArgs e)
        {
            ManagerAction(Const.Action.Remove);
        }

        protected void BtnDelete(object sender, EventArgs e)
        {
            ManagerAction(Const.Action.Delete);
        }

        #endregion
    }
}